//
//  MSToolkit.m
//  MinShengBank
//
//  Created by chen wei on 13-6-28.
//  Copyright (c) 2013年 xguanjia. All rights reserved.
//

#import "MSToolkit.h"
#import "ZipArchive.h"

//根据图片路径加载图片
extern UIImage* BundleImage(NSString* imageName) {
    return [UIImage imageNamed:imageName];
}

    //弹出消息框来显示消息
void ShowMessage(NSString* message) {
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil
											  cancelButtonTitle:@"确定"
											  otherButtonTitles:nil];
	[alertView show];
}
void ShowMessageinfo(NSString* message) {
    UIImageView *successAlert = nil;
    if (!isIPhone5) {
       successAlert = [[UIImageView alloc]initWithFrame:
           CGRectMake(50, 360, 220,30)];
    }else{
       successAlert = [[UIImageView alloc]initWithFrame:
           CGRectMake(50, 440, 220,30)];
    }
    
    successAlert.image =nil;
    successAlert.userInteractionEnabled = YES;
    
    UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(0, 0,220, 30)];
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font=[UIFont systemFontOfSize:18];
    label.text =message;
    
    CGSize sizeName = [message sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(MAXFLOAT, 30.0) lineBreakMode:NSLineBreakByWordWrapping];
    label.frame = CGRectMake((successAlert.frame.size.width - (sizeName.width+20))/2, 0, sizeName.width+20, 30);
    
    UIImageView *image_content =[[UIImageView alloc]initWithFrame:CGRectMake(0,0, 220, 30)];
    image_content.userInteractionEnabled = YES;
    [image_content addSubview:label];
    [successAlert addSubview:image_content];
    BSAppDelegate *app = (BSAppDelegate*)[[UIApplication sharedApplication]delegate];
    [app.window.rootViewController.view addSubview:successAlert];
    
    [UIView animateWithDuration:2.5
                     animations:^{
                         successAlert.alpha = 0;
                     }];
    [successAlert performSelector:@selector(removeFromSuperview)
                       withObject:nil
                       afterDelay:2.5];
}

//获取资源全路径
NSString* ResourcePath(NSString* fileName) {
	return [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"/%@", fileName];
}

//config目录：用来存放时间戳有效期内的景区下载文件:返回全路径
NSString* CatchPath(NSString* fileName) {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *mcPaths = [[paths objectAtIndex:0] stringByAppendingString:@"/config_cache"];
    //	[manager createDirectoryAtPath:mcPaths attributes:nil];
    [manager createDirectoryAtPath:mcPaths withIntermediateDirectories:NO attributes:nil error:nil];
	
	return mcPaths;
}

//temp目录：用来存放临时下载的文件:返回全路径
//一点说明：fileName格式支持如"suzhou/icon.png"带路径的格式，如果该文件夹路径不存在将自动创建出来
NSString* TemporaryPath(NSString* fileName) {
	return nil;
}

//下载文件temp目录：用来下载时临时存储文件，实现断点续传
NSString* DownloadTemporaryPath(NSString* fileName) {
	return nil;
}

//检查文件是否存在：此是ExistAtConfigPath和ExistAtTemporaryPath的综合
BOOL ExistAtPath(NSString* fileFullPath) {
	return [[fileFullPath pathExtension] length] > 0 &&
    [[NSFileManager defaultManager] fileExistsAtPath:fileFullPath];
}

NSString* templateFilePathWithUrl(NSString* url) {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *mcPaths = [[paths objectAtIndex:0] stringByAppendingString:@"/cache"];
    //	[manager createDirectoryAtPath:mcPaths attributes:nil];
    [manager createDirectoryAtPath:mcPaths withIntermediateDirectories:NO attributes:nil error:nil];
	NSString* result = [NSString stringWithFormat:@"%@/%@",  mcPaths,url];
    return result;
}
//删除所有catch文件
void RemoveCatchFiels(void) {
	
}

float CalcTextHight(UIFont *font, NSString* text, CGFloat width) {
	CGSize sz = [text sizeWithFont:font
                 constrainedToSize:CGSizeMake(width, 10000.0)];
	
	return sz.height;
}

float CalcTextWidth(UIFont *font, NSString* text, CGFloat width) {
	CGSize sz = [text sizeWithFont:font constrainedToSize:CGSizeMake(width, font.lineHeight)];
    
	return sz.width;
}

NSString* getCurrentTime(void)
{
    //更新最新授权时间
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];// HH:mm:ss
    NSString *dateString = [NSString stringWithFormat:@"%@",[dateFormat stringFromDate:[NSDate date]]];
    return dateString;
}

NSString*  DateStringWithTimeInterval(NSNumber* secs) {
	if ([secs intValue] <= 0) {
		return @"";
	} else {
		return StringFromDate([NSDate dateWithTimeIntervalSince1970:[secs doubleValue]], @"yyyy-MM-dd HH:mm");
	}
}

NSString* DateStringWithTimeIntervalOnlyDay(NSNumber* secs) {
	if ([secs intValue] <= 0) {
		return @"";
	} else {
		return StringFromDate([NSDate dateWithTimeIntervalSince1970:[secs doubleValue]], @"yyyy-MM-dd");
	}
}

NSString* StringFromDate(NSDate* aDate, NSString *aFormat) {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setTimeZone:[NSTimeZone defaultTimeZone]];
	[formatter setDateFormat:aFormat];
	NSString *dateString = [formatter stringFromDate:aDate];
	return dateString;
}

NSDate*   DateFromString(NSString* string, NSString* aFormat) {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
    [formatter setDateFormat:aFormat];
    NSDate *date = [formatter dateFromString:string];
    return date;
}

UIActionSheet* ActionSheet(NSString* title, NSArray* buttonsArray, id delegate) {
	if ([buttonsArray count] >= 1) {
		UIActionSheet * sheet = [[UIActionSheet alloc]
								 initWithTitle:title
								 delegate:delegate
								 cancelButtonTitle:nil
								 destructiveButtonTitle:nil
								 otherButtonTitles:nil];
		for (int i=0; i<[buttonsArray count]; i++) {
			NSString * label = [buttonsArray objectAtIndex:i];
			[sheet addButtonWithTitle:label];
		}
		[sheet addButtonWithTitle:@"取消"];
		sheet.cancelButtonIndex = [buttonsArray count];
		return sheet;
	}
	return nil;
}

const int factor[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };//加权因子
const int checktable[] = { 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 };//校验值对应表

int checkIDfromchar( char *ID )
{
    if (strlen(ID)!=18) {//验证18位
        return 0;
    }
    int IDNumber[ 19 ];
    for ( int i = 0; i < 18; i ++ )//相当于类型转换
        IDNumber[ i ] = ID[ i ] - 48;
    return checkID( IDNumber, ID );
}


int checkID( int IDNumber[], char ID[] )
{
    int i = 0;//i为计数
    int checksum = 0;
    for ( ; i < 17; i ++ )
        checksum += IDNumber[ i ] * factor[ i ];
    
    if ( IDNumber[ 17 ] == checktable[ checksum % 11 ] || ( ID[ 17 ] == 'x' && checktable[ checksum % 11 ] == 10 ))
        return 1;
    else
        return 0;
}

void showStatusBarMessage(NSString* message) {
    UIWindow * _window= [[UIWindow alloc]initWithFrame:CGRectMake(180, -20,100,20)];
    _window.windowLevel=UIWindowLevelAlert;
    _window.backgroundColor= [UIColor blackColor];
        //label
    UILabel*label = [[UILabel alloc]initWithFrame:CGRectMake(0,0,100,20)];
    label.textAlignment=NSTextAlignmentCenter;
    label.text=message;
    label.font = [UIFont systemFontOfSize:14];
    label.textColor= [UIColor whiteColor];
    label.backgroundColor= [UIColor clearColor];
    [_window addSubview:label];
    [_window makeKeyAndVisible];
    _window.backgroundColor = [UIColor clearColor];
        //animation
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:.3];
    _window.frame=CGRectMake(180,0,100,20);
    [UIView commitAnimations];
    
        //慢慢变透明，然后消失
    [UIView animateWithDuration:3
                     animations:^{
                         _window.alpha = 0;
                     }];
    [_window performSelector:@selector(removeFromSuperview)
                  withObject:nil
                  afterDelay:2];
        //1000~2000
}


void deleteSameObjects(NSMutableArray *stringArray){  //去除重复数据
    NSArray *ara = [stringArray copy];
    [stringArray removeAllObjects];
    NSSet *setArray = [[NSSet alloc]initWithArray:ara]; //nsset是无重复集合
    [stringArray addObjectsFromArray:[setArray allObjects]];
}

void startWaitCursor() {
    BSAppDelegate *appDelegate = (BSAppDelegate*)[[UIApplication sharedApplication] delegate];
	[appDelegate startLoading];
}

void stopWaitCursor() {
    BSAppDelegate *appDelegate = (BSAppDelegate*)[[UIApplication sharedApplication] delegate];
	[appDelegate stopLoading];
}

//压缩
NSString* zipfile(NSString *zipfile,NSArray *filepath)
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *dcoumentpath = [paths objectAtIndex:0];
    NSString *zipFil = [dcoumentpath stringByAppendingString:@"/"];
    NSString * zipPath = [ zipFil stringByAppendingString:zipfile];
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    @try
    {
        if([fileManager fileExistsAtPath:zipPath])
        {
            if(![fileManager removeItemAtPath:zipPath error:nil])
            {
                NSLog(@"Delete zip file failure.");
            }
        }
    }
    @catch (NSException * exception) {
        NSLog(@"%@",exception);
    }
    
    //如果把判断filepath为空去掉，要改上传是，所传key为photos的值
    //        if(filepath == nil || [filepath count] == 0)
    //            {
    //                CMBLOG(@"The files want zip is nil.");
    //                return nil;
    ////                return zipPath;
    //            }
    
    ZipArchive * zipArchive = [[ZipArchive alloc] init];
    [zipArchive CreateZipFile2:zipPath];
    
    for(NSString * fileName in filepath)
    {
        NSString * filePath = [zipFil stringByAppendingPathComponent:fileName];
        if([fileManager fileExistsAtPath:filePath])
        {
            [zipArchive addFileToZip:filePath newname:fileName];
        }
    }
    
    if([zipArchive CloseZipFile2])
    {
        NSLog(@"Create zip file success.");
        [zipArchive release];
        return zipPath;
    }
    [zipArchive release];
    
}

//解压缩
void unzipFile(NSString* aZipFile , NSString* aPath)
{
	ZipArchive* zip = [[ZipArchive alloc] init];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *dcoumentpath = [paths objectAtIndex:0];
	NSString* unzipto = [dcoumentpath stringByAppendingString:aPath] ;
	
	if( [zip UnzipOpenFile:aZipFile] )
	{
		BOOL ret = [zip UnzipFileTo:unzipto overWrite:YES];
		if( NO==ret )
		{
		}
		[zip UnzipCloseFile];
	}
	[zip release];
}

//解压缩_传入完整路径
void unzipFile_sourcepath(NSString* aZipFile , NSString* aPath)
{
	ZipArchive* zip = [[ZipArchive alloc] init];

	NSString* unzipto = aPath ;
	
	if( [zip UnzipOpenFile:aZipFile] )
	{
		BOOL ret = [zip UnzipFileTo:unzipto overWrite:YES];
		if( NO==ret )
		{
		}
		[zip UnzipCloseFile];
	}
	[zip release];
}


